package com.lx.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lx.common.Result;
import com.lx.dao.UserMapper;
import com.lx.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("login")
    public Result login(String name, String password, HttpSession session) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName, name);
        queryWrapper.eq(User::getPassword, password);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            session.setAttribute("myinfo", user);
            return new Result(1, "登录成功", user);
        }
        return new Result(0, "该用户未注册", null);
    }

    @RequestMapping("reg")
    public Result reg( String name, String password, String repassword, String email) {
        if (name == null || password == null || repassword == null || email == null) {
            return new Result(0, "参数错误", null);
        }
        if(!password.equals(repassword)) {
            return new Result(0, "密码不一致", null);
        }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getName, name);
        lqw.eq(User::getPassword, password);
        User user = userMapper.selectOne(lqw);
        if (user != null) {
            if (user.getPassword().equals(repassword)) {
                return new Result(0, "该用户已注册", null);
            }
        }
        user = new User();
        user.setName(name);
        user.setPassword(password);
        user.setEmail(email);
        userMapper.insert(user);
        return new Result(1, "注册成功", null);
    }

    @RequestMapping("myinfo")
    public Result myinfo(HttpSession session) {
        User user = (User) session.getAttribute("myinfo");
        return new Result(1, "成功", user);
    }

    @RequestMapping("logout")
    public Result logout(HttpSession session) {
        session.removeAttribute("myinfo");
        return new Result(1, "成功", null);
    }
}
